//
//  MYGSurgicalHistoryViewController.swift
//  MYDoctor
//
//  Created by 王振明 on 2024/4/23.
//

import UIKit
import MJRefresh

class MYGSurgicalHistoryViewController: MYGBaseController {
    var page:Int = 1
    var dataArr:[MYGOperationListModel] = []
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "手术记录"
        NotificationCenter.default.addObserver(self, selector: #selector(getDatasource), name: Notification.Name("MYGSurgicalHistoryViewController_getDatasource"), object: nil)
        initUi()
        getDatasource()
    }
    @objc func getDatasource(){
        MYGLoading.show()
        MYGNetwork<MYGSurgicalApi, MYGPageModel<MYGOperationListModel>>.request(target: .getSurgicalList(params: [:])) {[weak self] item in
                if self?.page == 1{
                    self?.dataArr.removeAll()
                }
                self?.dataArr.append(contentsOf: item.list)
                self?.tableView.reloadData()
                MYGLoading.hide()
                self?.tableView.mj_header?.endRefreshing()
                if item.page.total <= self?.dataArr.count ?? 0 {
                    self?.tableView.mj_footer?.endRefreshingWithNoMoreData()
                } else {
                    self?.tableView.mj_footer?.endRefreshing()
                }
            } failed: {[weak self] _, error in
                self?.tableView.mj_header?.endRefreshing()
                self?.tableView.mj_footer?.endRefreshing()
                MYGLoading.hide()
                MMYGHUD.showToast(text: error)
            }
    }
    @objc private func inviteAction(){
        self.navigationController?.pushViewController(MYGAddSurgicalViewController())
    }
    private func initUi(){
        view.backgroundColor = .white
        view.addSubview(tableView)
        tableView.snp.makeConstraints { make in
            make.left.right.top.equalToSuperview()
            make.bottom.equalToSuperview().offset(-50)
        }
        view.addSubview(addBtn)
        addBtn.snp.makeConstraints { make in
            make.left.right.bottom.equalToSuperview()
            make.height.equalTo(50)
        }
        addBtn.addCAGradientLayerColor(colors: [RGBA(r: 73, g: 117, b: 236, a: 1).cgColor,RGBA(r: 151, g: 179, b: 255, a: 1).cgColor], startPoint: CGPoint(x: 0, y: 0), endPoint: CGPoint(x: 1, y: 0))

    }
    
    lazy var tableView: UITableView = {
        let control = UITableView()
        control.showsVerticalScrollIndicator = false
        control.delegate = self
        control.dataSource = self
        control.rowHeight = UITableView.automaticDimension
        control.separatorStyle = .none
        control.register(cellWithClass: MYGSurgicalHistoryTableViewCell.self)
        control.mj_header = MJRefreshNormalHeader(refreshingBlock: {[weak self] in
            self?.page = 1
            self?.getDatasource()
        })
        control.mj_footer = MJRefreshAutoNormalFooter(refreshingBlock: {[weak self] in
            self?.page += 1
            self?.getDatasource()
        })
        return control
    }()
    private lazy var addBtn:UIButton = {
       let vi = UIButton()
        vi.setTitle("添加手术记录", for: .normal)
        vi.titleLabel?.font = .medium(17)
        vi.setTitleColor(.white, for: .normal)
        vi.addTarget(self, action: #selector(inviteAction), for: .touchUpInside)
        return vi
    }()
}
extension MYGSurgicalHistoryViewController:UITableViewDelegate,UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dataArr.count
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withClass: MYGSurgicalHistoryTableViewCell.self, for: indexPath)
        let model = dataArr[indexPath.row]
        cell.model = model
        return cell
    }
    
    func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
        let unbind = UIContextualAction(style: .normal, title: "删除") {[weak self]
            (action, view, completionHandler) in
            guard let `self` = self else {return}
            let data = self.dataArr[indexPath.row]
            let ids = "\(data.id)"
            self.toDelete(ids)
            completionHandler(true)
        }
        unbind.backgroundColor = UIColor.init(hexString: "#FF0000")
        
        let configuration = UISwipeActionsConfiguration(actions: [unbind])
        return configuration
    }
    func toDelete(_ id:String) {
        MYGLoading.show()
        MYGNetwork<MYGSurgicalApi, MYGEmptyModel>.request(target: .deleteSurgical(id: id)) {[weak self] item in
            MYGLoading.hide()
            self?.getDatasource()
        } failed: { _, error in
            MYGLoading.hide()
            MMYGHUD.showToast(text: error)
        }
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let model = dataArr[indexPath.row]
        let vc = MYGAddSurgicalViewController()
        vc.scan = true
        vc.detailId = model.id
        self.navigationController?.pushViewController(vc, animated: true)
    }
}
